package com.junyuan.fxf_pad.utils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.baidu.apistore.sdk.ApiCallBack;
import com.baidu.apistore.sdk.ApiStoreSDK;
import com.baidu.apistore.sdk.network.Parameters;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/8/2.
 */
public class GetWeather {
    Handler handler = new Handler();
    private ArrayList<String> weather = new ArrayList<>();


    public GetWeather(Handler handler) {
        this.handler = handler;
    }

    /**
     * 通过Api获取Json数据并调用解析方法,将解析后的数据返回
     *
     * @param url
     * @param city 城市名称
     * @return
     */
    public ArrayList<String> getWeather(String url, String city) {
        Parameters parameters = new Parameters();
        parameters.put("cityname", city);
        ApiStoreSDK.execute(url, ApiStoreSDK.GET, parameters, new ApiCallBack() {
            @Override
            public void onSuccess(int i, String s) {
                super.onSuccess(i, s);
                Log.d("mytag", "获取天气返回的json:"+s);
                weather = getWeatherEntity(s);
                Message message = new Message();
                message.what = Consts.GET_WEATHER_SUCCESS;
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("weather", weather);
                message.setData(bundle);
                handler.sendMessage(message);
            }

            @Override
            public void onComplete() {
                super.onComplete();
            }

            @Override
            public void onError(int i, String s, Exception e) {
                super.onError(i, s, e);
            }
        });

        return weather;
    }

    /**
     * 解析Json
     *
     * @param json
     * @return
     */
    private ArrayList<String> getWeatherEntity(String json) {
        ArrayList<String> weatherlist = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONObject jsonObject2 = jsonObject.getJSONObject("retData");
            String weather = jsonObject2.getString("weather");
            String temp = jsonObject2.getString("temp");

            weatherlist.add(weather);
            weatherlist.add(temp);
            Log.d("mytag", weather + " " + temp);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return weatherlist;
    }
}
